package com.mihu.stmall.manager.controller.api;


import com.github.pagehelper.PageInfo;
import com.mihu.stmall.manager.entiy.Goods;
import com.mihu.stmall.manager.entiy.Result;
import com.mihu.stmall.manager.service.GoodsPicService;
import com.mihu.stmall.manager.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
//相当于controller和ResponseBody的结合体
//1 将当前类放到Spring的bean容器
//2 所有处理方法 返回JSON格式的数据
@RequestMapping("/api/goods")
//给当前类
public class APIGoodsController {

    //自动注入service层对象
    @Autowired
    private GoodsService goodsService;

    @Resource
    private GoodsPicService goodsPicService;
    //添加 需要post请求
    @PostMapping
    public Result add(@RequestBody Goods goods){
        try {
            int code = goodsService.add(goods);
            //添加成功
            return Result.success();

        } catch (Exception e) {
            e.printStackTrace();
            //添加失败
            return Result.error(e.getMessage());
        }
    }
    //删除
    @DeleteMapping
    public Result remove(Integer id){
        try {
            int code = goodsService.remove(id);
            goodsPicService.removeByGoodsId(id);
            //成功
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            //失败
            return Result.error(e.getMessage());
        }
    }
    //修改
    @PutMapping
    public Result edit(@RequestBody Goods goods)  {
        try {
            int code = goodsService.edit(goods);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    @GetMapping
    public Result get( Integer page,Integer limit,Goods goods){
        if (page == null){
            List<Goods> list = goodsService.search(goods);

            return Result.success(list);
        }else {
            PageInfo pageInfo = goodsService.searchByPage(page,limit,goods);
            return Result.success(pageInfo);
        }
    }
    //根据ID进行查询
    //通过路径参数传递id
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") Integer id)  {
        //PathVariable取出路径中参数 绑定到id上
        Goods goods = null;
        try {
            goods = goodsService.getById(id);
            return Result.success(goods);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }


    }
}
